<template>
  <ul ref="menuRef" class="menu-container">
    <li v-for="(action, index) in actions" :key="index" class="menu-item" @click="action.action(componentId)">
      <span class="item-text">{{ action.text }}</span>
      <span class="item-shortcut">{{ action.shortcut }}</span>
    </li>
  </ul>
</template>

<script lang="ts" setup>
import { getParentElement } from '@/utils/utils'
import { ActionItem } from './createContextMenu'

const props = withDefaults(defineProps<{ actions: ActionItem[]; triggerClass?: string }>(), {
  triggerClass: 'edit-wrapper'
})

const menuRef = ref<HTMLElement | null>(null)
const componentId = ref('')

const triggerContextMenu = (e: MouseEvent) => {
  const menuElement = menuRef.value as HTMLElement
  const wrapperElement = getParentElement(e.target as HTMLElement, props.triggerClass)
  if (wrapperElement) {
    e.preventDefault()
    menuElement.style.display = 'block'
    menuElement.style.top = e.clientY + 'px'
    menuElement.style.left = e.clientX + 'px'
    // 挂载到 wrapper 节点上的 data-component-id
    const _componentId = wrapperElement.dataset.componentId
    if (_componentId) {
      componentId.value = _componentId
    }
  }
}

const handleClick = () => {
  const menuElement = menuRef.value as HTMLElement
  menuElement.style.display = 'none'
}

onMounted(() => {
  document.addEventListener('contextmenu', triggerContextMenu)
  document.addEventListener('click', handleClick)
})

onUnmounted(() => {
  document.removeEventListener('contextmenu', triggerContextMenu)
  document.removeEventListener('click', handleClick)
})
</script>
<style lang="scss" scoped>
.menu-container {
  display: none;
  position: absolute;
  background: #fff;
  z-index: 2000;
  width: 220px;
  // border: 1px solid #ccc;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);

  li {
    margin: 0;
    padding: 7px 16px;
    display: flex;
    justify-content: space-between;
    cursor: pointer;
    &:hover {
      background: #efefef;
    }
    .item-shortcut {
      color: #ccc;
    }
  }
}
</style>
